package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 对前端传过来的password进行md5加密，用来和数据库中的加密password比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    //新增员工
    @Override
    public void save(EmployeeDTO employeeDTO) {
        System.out.println("当前线程id为:"+Thread.currentThread().getId());
        //在保存数据到数据库时，注意从dto类到实体类的转化
        Employee employee = new  Employee();
        BeanUtils.copyProperties(employeeDTO,employee);//对两个类似的bean中的值进行copy
        //对剩余没被copy的值进行手动赋值
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));//用常数代替密码，进行md5加密操作
        employee.setStatus(StatusConstant.ENABLE);//默认设置为启动
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setCreateUser(BaseContext.getCurrentId());
//        employee.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.insert(employee);

    }

    @Override
    //分页查询功能
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        //若自己手写sql查询语句为：select * from employee limit 0,10
        //可以采用pagehelper插件帮助实现分页功能
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        //注意从数据库取出的数据类型应该为Employee而不是DTO类型
        /*
        由于使用了动态查询，因此没有使用注解编写sql，而是在resource/mapper中的mapper.xml中动态编写sql语句
         */
        Page<Employee> page = employeeMapper.pageQuery(employeePageQueryDTO);
        long total = page.getTotal();
        List<Employee> result = page.getResult();
        PageResult pageResult = new PageResult(total,result);
        return pageResult;
    }

    @Override
    //员工状态启用或禁用
    public void startOrStop(Integer status, Long id) {
        //这里要使用employee对象，因为传入了status参数
        //两种构造方式，一种是传统set方法构建，一种是使用build注解构建
        /*
        Employee employee = new Employee();
        employee.setStatus(status);
        employee.setId(id);
        */

        Employee employee=Employee.builder()
                .id(id)
                .status(status)
                .build();

        employeeMapper.update(employee);
    }

    @Override
    //根据id查询员工信息
    public Employee getById(Long id) {
        Employee employee=employeeMapper.getById(id);
        //对返回的密码再次进行处理，确保安全性
        employee.setPassword("****");
        return employee;
    }

    @Override
    //更新员工信息
    public void update(EmployeeDTO employeeDTO) {
        //此时可以使用EmployeeMapper.xml中的update方法，但是要注意从dto到实体类的转换
        Employee employee = new  Employee();
        BeanUtils.copyProperties(employeeDTO,employee);//属性拷贝
        //employee.setUpdateTime(LocalDateTime.now());//更新修改时间
        //employee.setUpdateUser(BaseContext.getCurrentId());//更新修改人id

        employeeMapper.update(employee);
    }

}
